package com.dongnam.quanly.web.util;

import java.util.Date;

import javax.faces.application.FacesMessage;

import org.hibernate.StaleObjectStateException;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.JDBCConnectionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.web.JSFUtility;

public class MessageUtil {

	private static final Logger logger = LoggerFactory.getLogger(MessageUtil.class);

	public static String addErrorMsg(String msgKey, String e, Date date) {
		String message = LocaleMessages.getString(msgKey, e, date);
		JSFUtility.setJSFFacesMessage(FacesMessage.SEVERITY_ERROR, message, message);
		return message;
	}

	public static String getDescriptionOfDBException(Exception e) {
		String message;
		if (e instanceof DatabaseException) {
			Throwable cause = e.getCause();
			if (cause instanceof StaleObjectStateException) {
				message = LocaleMessages.getString("db_error_reason_concurrentAccess");
				return message;
			} else if (cause instanceof ConstraintViolationException) {
				message = LocaleMessages.getString("db_error_reason_integrityViolation");
				return message;
			} else if (cause instanceof JDBCConnectionException) {
				message = LocaleMessages.getString("db_error_reason_connectionException");
				return message;
			}
		}
		message = e.getMessage();
		return message;
	}

	public static void logDBException(String description, Exception e) {
		logger.error(description, e);
	}
}
